<template>
    <div class="chatContainer">
        <div class="titleBox">
            <div class="title">{{ ChatViewApi.getChatTitle(props.chatTitle) }}</div>
            <div class="deleteChat" @click="deleteChat">
                <span class="iconfont icon-likesprogramhuishouzhan"></span>
            </div>
        </div>
        <div class="chatHistoryBox">
            <div class="chatHistoryAndInput">
                <div class="chatHistorys" ref="chatHistorys" @scroll="handleScroll">
                    <ChatHistory v-for="(item, index) in props.chatHistoryList" :key="index" :chatHistory="item" />
                </div>
                <div class="chatInputBox" @keydown="handleKeyDown">
                    <!-- 编辑器 -->
                    <div class="inputEditor">
                        <EditorComponent ref="editorComponent" :noToolShadow="true" :fontSize="15"
                         :toolbarConfig="['insertLink', 'insertImage', 'insertVideo', 'emotion']" />
                    </div>
                    <!-- 按钮 -->
                    <div class="buttonBox">
                        <div class="prompt">Shift + Backspace : <span class="iconfont icon-likesprogramhuishouzhan"></span> 清除输入框</div>
                        <div class="prompt">Shift + Enter : <span class="iconfont icon-likesprogramhuiche"></span> 换行</div>
                        <div class="prompt">Enter : <span class="iconfont icon-likesprogramfasong"></span> 发送</div>
                        <div class="button clearButton" @click="clearMessage">清除<span class="iconfont icon-likesprogramhuishouzhan"></span></div>
                        <div class="button sendButton" @click="sendMessage">发送<span class="iconfont icon-likesprogramfasong"></span></div>
                    </div>
                </div>
            </div>
            <div class="memberList" v-if="props.memberList?.length > 0">
            </div>
        </div>
    </div>
</template>
<script lang="ts">
import { defineComponent, nextTick, onMounted, ref, watch } from 'vue';
import { ChatViewApi } from '@/components/message/ChatList.vue';
import EditorComponent from '@/components/EditorComponent.vue'; 
import ChatHistory, { ChatHistoryData, Permission } from '@/components/message/chatContainer/ChatHistory.vue';
export default defineComponent({
    name: 'chatContainer',
});
// 聊天记录
export interface ChatMemberList {
    userId: number;
    userName?: string;
    avatar?: string;
    permission?: keyof typeof Permission;
}
</script>
<script setup lang="ts">
    const editorComponent = ref(null); // 获取编辑器组件实例
    const props = withDefaults(defineProps<{
        chatTitle?: string;
        chatHistoryList?: ChatHistoryData[];
        memberList?: ChatMemberList[];
    }>(), {
        chatTitle: '',
        chatHistoryList: () => [],
        memberList: () => [],
    });

    // 定义事件
    const emit = defineEmits<{
        // 删除事件
        (e: 'sendMessage', message: string): void;
        (e: 'deleteChat'): void;
    }>();

    // 发送消息
    const sendMessage = async () => {
        emit("sendMessage", editorComponent.value.getText()); // 响应 发送消息事件
        editorComponent.value.Focus(); // 重新聚焦编辑器
        editorComponent.value.clear(); // 清空编辑器
        await scrollToBottom(true); // 滚动到底部
    };

    // 清除消息
    const clearMessage = () => {
        editorComponent.value.Focus(); // 重新聚焦编辑器
        editorComponent.value.clear(); // 清空编辑器
    };

    // 处理键盘事件
    const handleKeyDown = (e: KeyboardEvent) => {
        // 如果按下了Enter键且没有按下Shift键，则发送消息
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault(); // 阻止默认换行行为
            sendMessage(); // 发送消息
        }

        // Shift+Backspace清除（同时兼容key和keyCode）
        if ((e.key === 'Backspace' || e.keyCode === 8) && e.shiftKey) {
            e.preventDefault();
            clearMessage();
        }
    };

    const chatHistorys = ref<HTMLElement | null>(null);
    const isUserScrolledUp = ref(false); // 标记用户是否手动滚动了聊天窗口
    const hasNewMessages = ref(false); // 标记是否有新的消息
    let isProgrammaticScroll = false; // 标记是否程序触发的滚动

    // 处理滚动事件
    const handleScroll = async () => {
        if (!chatHistorys.value) return;
        
        isProgrammaticScroll = true; // 加锁

        await nextTick(); // 等待 Vue 更新 DOM
        // 计算用户是否滚动了窗口（距离底部50px以内不算滚动）
        const threshold = 100;
        const { scrollTop, scrollHeight, clientHeight } = chatHistorys.value;
        const currentlyScrolledUp = scrollTop + clientHeight < scrollHeight - threshold;
        // 如果用户从滚动状态回到底部，重置状态
        if (isUserScrolledUp.value && !currentlyScrolledUp) {
            isUserScrolledUp.value = false;
            hasNewMessages.value = false;
        } else {
            isUserScrolledUp.value = currentlyScrolledUp;
        }

        // 滚动结束后解锁（400ms后）
        setTimeout(() => isProgrammaticScroll = false, 500); 
    };

    // 滚动到底部
    const scrollToBottom = async (force?: boolean) => {
        if (!force && isProgrammaticScroll) return; // 忽略程序触发的滚动
        if (force) isUserScrolledUp.value = false;
        await nextTick(); // 等待 Vue 更新 DOM
        if (chatHistorys.value && !isUserScrolledUp.value) {
            chatHistorys.value.scrollTo({
                top: chatHistorys.value.scrollHeight,
                behavior: 'smooth'
            });
            hasNewMessages.value = false;
        } else {
            hasNewMessages.value = true;
        }
    };

    // 监听 chatHistoryList 变化时，滚动到底部
    watch(() => props.chatHistoryList, async () => {
        await scrollToBottom();
    }, { immediate: true, deep: true } // 初始化时立即执行一次 , 深度监听数组变化
    );

    // 初始化时滚动到底部
    onMounted(() => {
        nextTick(async () => {
            editorComponent.value.Focus();
            await scrollToBottom();
        });
    });

    // 重置面板
    const resetPanel = () => {
        clearMessage(); // 清空消息
        isUserScrolledUp.value = false; // 标记用户是否手动滚动了聊天窗口
        hasNewMessages.value = false; // 标记是否有新的消息
        isProgrammaticScroll = false; // 标记是否程序触发的滚动
        // 滚动到底部
        nextTick(async () => {
            editorComponent.value.Focus();
            await scrollToBottom();
        });
    };

    // 删除会话
    const deleteChat = async () => {
        emit('deleteChat');
    };

    // 暴露方法
    defineExpose({
        scrollToBottom,
        resetPanel
    });
</script>


<style src="@/assets/icons/iconfont.css" scoped></style>
<style scoped>
/* 聊天面板 */
.chatContainer {
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
/* 标题 */
.chatContainer .titleBox {
    width: 100%;
    height: 70px;
    font-size: 16px;
    padding-left: 25px;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    border-bottom: 1px solid rgba(100, 100, 100, .1);
    background-color: rgba(255, 255, 255, .5);
    backdrop-filter: blur(2rem);
    -webkit-backdrop-filter: blur(2rem);
    -moz-backdrop-filter: blur(2rem);
    -ms-backdrop-filter: blur(2rem);
}
.chatContainer .titleBox .title {
    width: calc(100% - 60px);
    /* 溢出省略号 */
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.chatContainer .titleBox .deleteChat {
    width: 40px;
    height: 40px;
    margin-right: 20px;
    cursor: pointer;
    font-size: 24px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 10px;
    color: rgba(255, 0, 0, 1);
    transition: all .3s;
}
.chatContainer .titleBox .deleteChat:hover {
    background-color: rgba(255, 0, 0, 0.1);
}
.chatContainer .titleBox .deleteChat:active {
    background-color: rgba(255, 0, 0, 0.2);
    color: rgba(255, 0, 0, .8);
    transition: all .1s;
}

/* 历史聊天框 */
.chatContainer .chatHistoryBox {
    width: 100%;
    flex: 1;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
}
.chatContainer .chatHistoryBox .chatHistoryAndInput {
    height: 100%;
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

/* 聊天记录 */
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatHistorys {
    width: 100%;
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    overflow-y: auto;
    position: relative;
    z-index: 1;
}

/* 输入框 */
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox {
    width: 100%;
    height: 230px;
    flex-shrink: 0;
    display: flex;
    position: relative;
    z-index: 2;
    flex-direction: column;
    align-items: center;
    border-top: 1px solid rgba(100, 100, 100, .1);
    background-color: rgba(255, 255, 255, .1);
    backdrop-filter: blur(2rem);
    -webkit-backdrop-filter: blur(2rem);
    -moz-backdrop-filter: blur(2rem);
    -ms-backdrop-filter: blur(2rem);
}
/* 输入框 */
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox .inputEditor {
    width: 100%;
    height: calc(100% - 50px);
}
/* 按钮列表 */
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox .buttonBox {
    width: 100%;
    height: 50px;
    padding: 0 20px;
    display: flex;
    gap: 20px;
    align-items: center;
    justify-content: flex-end;
}

.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox .buttonBox .button {
    width: 75px;
    height: 30px;
    border-radius: 5px;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all .3s;
    box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);
}
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox .buttonBox .button .iconfont {
    font-size: 17px;
    padding-left: 5px;
}
/* 发送按钮 */
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox .buttonBox .button.sendButton {
    background-color: rgba(65, 185, 255, 1);
    color: rgba(255, 255, 255, 1);
}
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox .buttonBox .button.sendButton:hover {
    background-color: rgba(65, 185, 255, 0.8);
    box-shadow: 0px 0px 5px rgba(0, 0, 0, .2);
}
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox .buttonBox .button.sendButton:active {
    background-color: rgba(65, 185, 255, 1);
    transition: all .1s;
}
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox .buttonBox .button.sendButton:active .iconfont {
    font-size: 19px;
}
/* 清除按钮 */
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox .buttonBox .button.clearButton {
    background-color: rgba(255, 255, 255, 1);
}
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox .buttonBox .button.clearButton:hover {
    background-color: rgba(240, 240, 240, 1);
    box-shadow: 0px 0px 5px rgba(0, 0, 0, .2);
}
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox .buttonBox .button.clearButton:active {
    background-color: rgba(255, 255, 255, 1);
    transition: all .1s;
}
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox .buttonBox .button.clearButton:active .iconfont {
    font-size: 19px;
}

/* 提示语句 */
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox .buttonBox .prompt {
    font-size: 12px;
    color: rgba(0, 0, 0, .5);
    padding: 0px 5px;
}
.chatContainer .chatHistoryBox .chatHistoryAndInput .chatInputBox .buttonBox .prompt .iconfont {
    font-size: 14px;
}

/* 成员列表 */
.memberList {
    width: 180px;
    height: 100%;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    border-left: 1px solid rgba(100, 100, 100, .1);
    background-color: rgba(255, 255, 255, .1);
    backdrop-filter: blur(2rem);
    -webkit-backdrop-filter: blur(2rem);
    -moz-backdrop-filter: blur(2rem);
    -ms-backdrop-filter: blur(2rem);
}
</style>